// Copyright [2020] <unknown>
#include <bits/stdc++.h>
using namespace std;
#define ONLINE_JUDGE
#ifndef ONLINE_JUDGE
#define dbg(x...)                             \
    {                                         \
        cerr << "\033[32;1m" << #x << " -> "; \
        err(x);                               \
    }
void err() { cerr << "\033[39;0m" << endl; }
template <typename T, typename... A>
void err(T a, A... x) {
    cerr << a << ' ';
    err(x...);
}
#else
#define dbg(...)
#endif

#define sz(x) ((int)x.size())

typedef long long LL;

const int N = 1e5 + 50;

vector<pair<int, int>> E, e;
vector<int> G[N], g[N];

void add(int u, int v, int w, vector<int> G[], vector<pair<int, int>> &E) {
    G[u].push_back(E.size());
    E.emplace_back(v, w);
}

int n;

int sec[N];

int a[N], c[N];

bool off[N];

int vis[N];

bool dfs(int u, int &mine, int col) {
    dbg(u);
    bool res = false;
    vis[u] = col;
    for (int eid : G[u]) {
        int v = E[eid].first;
        mine = min(mine, E[eid].second - sec[u]);
        if (vis[v] == col)
            return true;
        else if (vis[v])
            return false;
        res |= dfs(v, mine, col);
    }
    return res;
}


int main(int argc, char const *argv[]) {
    scanf("%d", &n);

    for (int i = 1; i <= n; ++i) {
        scanf("%d%d", &a[i], &c[i]);
        add(a[i], i, c[i], g, e);
    }
    LL ans = 0;
    for (int i = 1; i <= n; ++i) {
        int maxe = -1;
        for (int eid : g[i]) {
            if (maxe == -1 || e[eid].second > e[maxe].second)
                maxe = eid;
        }
        sec[i] = 0;
        for (int eid : g[i])
            if (eid != maxe) {
                ans += e[eid].second;
                sec[i] = max(sec[i], e[eid].second);
                off[eid] = true;
            }
    }
    assert(e.size() == n);
    for (int i = 0; i < n; ++i)
        if (!off[i])
            add(a[i + 1], i + 1, c[i + 1], G, E);

    int root = 0;
    for (int i = 1; i<=n; ++i) {
        if (vis[i])
            continue;
        ++root;
        int mine = 1e9;
        bool flag = dfs(i, mine, i);
        if (flag)
            ans += mine;
        dbg(i, ans, flag);
    }
    if (root == 1) {
        puts("0");
        return 0;
    }

    cout << ans << endl;

    return 0;
}
